/* eslint-disable */
import axios from 'axios'
import Vue from 'vue'
import { Loading } from 'element-ui';
import { toast } from './toast'
import _ from 'lodash';
let loadingInstance; //loading 实例
let needLoadingRequestCount = 0; //当前正在请求的数量

function showLoading() {
    let main = document.querySelector('#page-main')
    if (main) {
        if (needLoadingRequestCount === 0 && !loadingInstance) {
            loadingInstance = Loading.service({
                fullscreen: true,
                target: main,
                text: '数据加载中......',
                customClass: "loadingClass",
                background: 'rgba(207,204,204,0.1)'
            });
        }
        needLoadingRequestCount++;
    }
}

function closeLoading() {
    Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        needLoadingRequestCount--;
        needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 保证大于等于0
        if (needLoadingRequestCount === 0) {
            if (loadingInstance) {
                hideLoading()
            }
        }
    });
}
//防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
//因为有时会碰到在一次请求完毕后又立刻又发起一个新的请求的情况（比如删除一个表格一行后立刻进行刷新）
//这种情况会造成连续 loading 两次，并且中间有一次极短的闪烁。通过防抖可以让 300ms 间隔内的 loading 便合并为一次，避免闪烁的情况。
var hideLoading = _.debounce(() => {
    loadingInstance.close();
    loadingInstance = null;
}, 2000);


axios.interceptors.request.use(function(config) {
    showLoading()
    return config
}, function(error) {
    closeLoading()
    return Promise.reject(error)
})

axios.interceptors.response.use(function(response) {
    closeLoading()
    return response
}, function(error) {
    closeLoading()
    toast('未知错误')
    return Promise.reject(error)
})

async function http(options = { method: 'get' }) {
    const method = options.method
    options.headers = options.headers ? options.headers : {}
    if (method === 'get' || method === 'GET') {
        if (options.data) {
            options.data = Object.assign({}, options.data)
        } else {
            options.data = {}
        }
        options.params = options.data
    } else {
        if (options.data) {
            options.data = Object.assign({}, options.data)
        } else {
            options.data = {}
        }
    }
    options.baseURL = ''
    options.timeout = 100000 // 请求超时时间
    const response = await axios(options)
    if (response.status === 200) {
        closeLoading()
        if (response.data.statusCode === 500) {
            return toast('未知错误')
        }
        return response.data
    } else {
        closeLoading()
        toast('未知错误')
    }
}
export { http }